import type { ShallowRef } from 'vue'
import type {
  EnergyDataReportInformant,
  EnergyDataReportList,
  InitInputIndex,
  LoadListFunction,
  ReportColumnsItem,
} from '../types'

function useReportAction(option: Partial<{
  title: ComputedRef<string>
  fromGovernmentSide: ComputedRef<boolean>
  flattenColumns: ComputedRef<ReportColumnsItem[]>
  seriesNo: Ref<string>
  lists: ShallowRef<
      EnergyDataReportList<{
        key: string
        value: string | number
        editable?: boolean
        [propName: string]: any
      }>[]
    >
  informant: ComputedRef<EnergyDataReportInformant>
  inputIndex: Ref<number>
  rowIndex: Ref<number>
  showLineNumber: Ref<boolean>
  visible: Ref<boolean>
  left: Ref<number>
  top: Ref<number>
  loadList: LoadListFunction
  year: ComputedRef<number | string>
  quarter: ComputedRef<number | string>
  enterpriseId: ComputedRef<number | string>
}>) {
  const {
    loadList,
    inputIndex,
    rowIndex,
    visible,
    year,
    quarter,
    enterpriseId,
  } = toValue(option)

  const clickHandler = (evt: Event, index?: number) => {
    if (evt.target) {
      (evt.target as HTMLInputElement).select()

      if (inputIndex) {
        inputIndex.value = Number(
          (evt.target as HTMLInputElement).dataset.inputIndex,
        )
      }

      if (rowIndex && typeof index !== 'undefined') {
        rowIndex.value = index
      }

      if (visible) {
        visible.value = false
      }
    }
  }

  // 给每个input添加索引
  const initInputIndex: InitInputIndex = () => {
    const inputs = document.querySelectorAll('.input-cell input')
    inputs.forEach((input, index) => {
      (input as HTMLElement).dataset.inputIndex = `${index}`
    })
  }

  const loadPrevData = () => {
    let y = toValue(year)
    let q = toValue(quarter)
    if (Number(q) === 5) {
      // 年度
      y = Number(y) - 1
    }
    else {
      q = Number(q) - 1
      if (q === 0) {
        y = Number(y) - 1
        q = 4
      }
    }
    console.log('loadList: ', y, q, enterpriseId?.value)
    if (y && q) {
      loadList?.({
        year: y,
        quarter: q,
        tenantId: toValue(enterpriseId),
      })
    }
  }

  return {
    loadPrevData,
    clickHandler,
    initInputIndex,
  }
}

export default useReportAction
